import express from 'express';
import bcrypt from 'bcryptjs';
import { body, validationResult } from 'express-validator';
import { getOne, executeQuery } from '../config/database.js';
import { generateToken, authenticateToken } from '../middleware/auth.js';

const router = express.Router();

// 用户登录
router.post('/login', [
  body('username').trim().notEmpty().withMessage('用户名不能为空'),
  body('password').notEmpty().withMessage('密码不能为空')
], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { username, password } = req.body;

    // 查找用户
    const user = await getOne(
      'SELECT id, username, password, name, role, phone FROM users WHERE username = ?',
      [username]
    );

    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 验证密码 (暂时使用明文密码)
    if (password !== user.password) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 生成JWT令牌
    const token = generateToken(user.id, user.role);

    // 移除密码字段
    const { password: _, ...userInfo } = user;

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: userInfo
      }
    });

  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取当前用户信息
router.get('/profile', authenticateToken, async (req, res) => {
  try {
    const user = req.user;
    
    // 根据角色获取额外信息
    let extraInfo = {};
    
    if (user.role === 'teacher') {
      // 获取教师负责的班级
      const classes = await executeQuery(`
        SELECT c.id, c.name, c.grade 
        FROM classes c
        INNER JOIN teacher_classes tc ON c.id = tc.class_id
        WHERE tc.teacher_id = ?
      `, [user.id]);
      
      extraInfo.classes = classes;
    } else if (user.role === 'driver') {
      // 获取司机信息
      const driverInfo = await getOne(
        'SELECT license_no, bus_no FROM drivers WHERE user_id = ?',
        [user.id]
      );
      
      extraInfo.driverInfo = driverInfo;
    }

    res.json({
      success: true,
      data: {
        ...user,
        ...extraInfo
      }
    });

  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 修改密码
router.put('/change-password', [
  authenticateToken,
  body('currentPassword').notEmpty().withMessage('当前密码不能为空'),
  body('newPassword').isLength({ min: 6 }).withMessage('新密码至少6位')
], async (req, res) => {
  try {
    // 验证输入
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '输入验证失败',
        errors: errors.array()
      });
    }

    const { currentPassword, newPassword } = req.body;
    const userId = req.user.id;

    // 获取当前密码哈希
    const user = await getOne(
      'SELECT password FROM users WHERE id = ?',
      [userId]
    );

    // 验证当前密码 (暂时使用明文密码)
    if (currentPassword !== user.password) {
      return res.status(400).json({
        success: false,
        message: '当前密码不正确'
      });
    }

    // 更新密码 (暂时使用明文存储)
    await executeQuery(
      'UPDATE users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [newPassword, userId]
    );

    res.json({
      success: true,
      message: '密码修改成功'
    });

  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 令牌验证
router.post('/verify-token', authenticateToken, (req, res) => {
  res.json({
    success: true,
    message: '令牌有效',
    data: req.user
  });
});

export default router;
